1. Template Method Example

1. Template Method Example

1.1. Introduction

The Template pattern as defined in the GoF book

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the classes of the elements on which it operates.

In java you would typically have an abstract class with at least one abstract method that has to be implemented by each concrete subclass and a concrete template method that uses the abstract method(s). In general the template method itself will be final.

1.2. Example - Implementing the Visits

We already used this pattern in the Composite Pattern to make the visitor traverse each node.

In order to simplify the concrete implementations Table , Row and Cell we moved the common code to MComposite.accept(MVisitor) made that method final and introduced the abstract method localAccept(MVisitor) , each concrete subclass then only has to implement the single method in a very simple way

@Override
protected void localAccept(MVisitor visitor) {
	visitor.visit(this);
}

This are the actual parts of the code that matter.

public abstract class MObject {
[...]
	protected abstract void localAccept(MVisitor visitor);
[...]
}

public abstract class MComposite extends MObject {
	[...]
	@Override
	public final void accept(MVisitor visitor) {
		visitor.enter(this);
		localAccept(visitor);
		for (MObject child : children) {
			child.accept(visitor);
		}
		visitor.leave(this);
	}
}